<?php

/***************************************************************\
* FILE:		functions.inc
* SECTION:	core
* FUNCTION:	provide various functions for dir browsing etc
* USES:		$PATH_INFO
* INCLUDES:	none	
* PRODUCES:	f.e. $PAGE['directory_tree'] vars
* LAUNCHES:	none
\***************************************************************/

/**
 * function to calculate directory tree from url
 */
function calculate_page($path) {

	global $PAGE, $CONFIG;

	if (ereg("^/?$", $path))
		redirect($CONFIG['homedir']);
	
	$PAGE['fullpath'] = $path;
	$PAGE['dirpath'] = ereg_replace("/$","",ereg("\.",$path)?dirname($path):$path);

	$dirs = explode("/",substr($PAGE['dirpath'],1));	

	$parent = 0;
	
	for ($i = 0; $i < count($dirs); $i++) {
		
		$dir = $dirs[$i];
	
		$sql = db_query_select(array(array("*"), array("parent_id"), array("sorting_name", "sorting_sql")), 
				       array("DIRECTORY", "DIRECTORY_TREE", "SORTING"), 
					     "DIRECTORY.dir_id = DIRECTORY_TREE.child_id AND DIRECTORY_TREE.parent_id = $parent " . 
					     "AND DIRECTORY.name = '$dir' AND DIRECTORY.sorting_id = SORTING.sorting_id");
		
		$sqlresult = db_do_query($sql);
		
		if (db_num_rows($sqlresult) != 1)
			errorpage(2);
			
		$result = db_fetch_array($sqlresult);
		
		$PAGE['directory_tree'][] = $result;

		$parent = $result['dir_id'];
		
	}
	
	$PAGE['dir_depth'] = count($PAGE['directory_tree']);
	
	if (ereg("\.", $path)) {
		$PAGE['page'] = basename($path);
		$PAGE['type'] = substr(strstr($PAGE['page'],"."),1);
		$PAGE['id'] = substr($PAGE['page'],0,strpos($PAGE['page'],"."));
	} else {
		$PAGE['type'] = "dir";
	}
	
	$THISDIR = $PAGE['directory_tree'][$PAGE['dir_depth']-1];

	$main = $THISDIR['body_main'] ? $THISDIR['body_main'] : -1;
	$footer = $THISDIR['body_footer'] ? $THISDIR['body_footer'] : -1;
	
	$sql = db_query_select(array(array("body"), "(body_id = $main) as is_main"), array("BODY", "DUMMY"), "body_id IN ($main,$footer)");
	$sqlresult = db_do_query($sql);
	$PAGE['body_main_id'] = $main;
	$PAGE['body_footer_id'] = $footer;
	while ($b = db_fetch_array($sqlresult))
		if ($b['is_main'])
			$PAGE['body_main'] = db_desqlize($b['body']);
		else
			$PAGE['body_footer'] = db_desqlize($b['body']);
	

}

/**
 * function to generate the menu tree
 */
function generate_menu() {
	global $PAGE;
	$MENU = array();
	
	// 1. get directories
	$order = "DIRECTORY_TREE.parent_id ASC, DIRECTORY_TREE.rank ASC";
	
	$group = "DIRECTORY_TREE.child_id, DIRECTORY_TREE.parent_id";
	
	$sql = db_query_select(	array(array(), "DIRECTORY.*, DIRECTORY_TREE.*"), array("DIRECTORY_TREE INNER JOIN DIRECTORY ON child_id = dir_id", "DUMMY"), 
				      1, $order, "", $group);

	$menu_dirs = db_do_query($sql);

	// if logged in, also check readings
	if ($_SESSION['user_id']) {
		$menu_items = db_do_query(db_query_select(array(array(), "child_id, COUNT(item_id) AS items"), 
					                  array("((DIRECTORY_TREE INNER JOIN SUB_IN ON child_id = dir_id) INNER JOIN ITEM_IN " .
								"ON SUB_IN.sub_id = ITEM_IN.sub_id)", "DUMMY"), "deleted != 1", $order, "", $group));
		$menu_reads = db_do_query(db_query_select(array(array(), "child_id, COUNT(HAS_READ.item_id) AS read_count"), 
							  array("((DIRECTORY_TREE INNER JOIN SUB_IN ON child_id = dir_id) INNER JOIN ITEM_IN " .
								"ON SUB_IN.sub_id = ITEM_IN.sub_id) INNER JOIN HAS_READ ON HAS_READ.item_id = ITEM_IN.item_id", "DUMMY"), 
							  "user_id = {$_SESSION['user_id']} AND deleted != 1", $order, "", $group));
	}

	// 2. get access restrictions

	$select = array(array("parent_id", "rank"), array("dir_id"), array("allow"));

	$from = array("DIRECTORY_TREE", "DIRECTORY", "ACCESS_RULE");

	$where = "DIRECTORY_TREE.child_id = ACCESS_RULE.dir_id AND \n\t";
	$where .= "DIRECTORY_TREE.child_id = DIRECTORY.dir_id AND \n\t";
	$where .= "ACCESS_RULE.action_id = 1 AND \n\t(\n\t\t";
	if ($_SESSION['user_id']) {
		$where .= "ACCESS_RULE.user_id = {$_SESSION['user_id']} OR \n\t\t";
		for ($i = 0; $i < count($_SESSION['user_groups']); $i++)
			$groups .= $_SESSION['user_groups'][$i].",";
		$groups .= "-1";
		$where .= "ACCESS_RULE.usergroup_id IN ($groups) OR \n\t\t";
	}
	$where .= "ACCESS_RULE.ipstring LIKE '".$_SERVER["REMOTE_ADDR"]." - ".$_SERVER["HTTP_X_FORWARDED_FOR"]."' OR \n\t\t";
	$where .= "ACCESS_RULE.guest > 0\n\t)";
	
	$order = "DIRECTORY_TREE.parent_id ASC, DIRECTORY_TREE.rank ASC, ACCESS_RULE.rank ASC";
	
	$sql = db_query_select($select, $from, $where, $order);
	
	$menu_access = db_do_query($sql);
	
	// 3. construct menu tree
	
	$row_access = db_fetch_array($menu_access);
	$MENU[0]['access'] = "ALLOW";
	$MENU[0]['children'] = array();
	
	while ($row = db_fetch_array($menu_dirs)) {
		
		// add plain info
		$MENU[$row['dir_id']] = $row;
		
		// add ignore info
		if ($_SESSION['user_id'] and $ignored[$row['dir_id']]) 
			$MENU[$row['dir_id']]['ignored'] = 1;

		// add access info
		$MENU[$row['dir_id']]['access'] = "INHERIT";
		if ($row_access['dir_id'] == $row['dir_id']) {
			$MENU[$row['dir_id']]['access'] = $row_access['allow'] ? "ALLOW" : "DENY";
			while ($row_access['dir_id'] == $row['dir_id'])
				$row_access = db_fetch_array($menu_access); 
		}
		
		// add to parent dir
		$MENU[$row['parent_id']]['children'][$row['rank']] = $row['dir_id'];
		$MENU[$row['child_id']]['parents'] = array();
		$MENU[$row['child_id']]['children'] = array();
	}
	
	// add parents
	$parentstuff = db_do_query(db_query_select(array(array("*")), array("DIRECTORY_TREE"), 1));
	while ($p = db_fetch_array($parentstuff))
		if ($p['child_id'])
			array_push($MENU[$p['child_id']]['parents'], $p['parent_id']);
			
	if ($_SESSION['user_id']) {
	
		// add readings info
		while ($row_reads = db_fetch_array($menu_reads)) {
			$MENU[$row_reads['child_id']]['read_items'] = $row_reads['read_count'];
		}
		while ($row_items = db_fetch_array($menu_items)) {
			$MENU[$row_items['child_id']]['items'] = $row_items['items'];
			$MENU[$row_items['child_id']]['new_items'] = $MENU[$row_items['child_id']]['items'] - $MENU[$row_items['child_id']]['read_items'];
		}
		
		// add ignore info
		$menu_ignore = db_do_query(db_query_select(array(("*")), array("IGNORE_DIR"), "user_id = {$_SESSION['user_id']}"));
		while ($ri = db_fetch_array($menu_ignore))
			$MENU = util_set_ignored($ri['dir_id'], $MENU);
	}
	
	if ($_SESSION['nick'] == "sareth") {
		echo "<pre>";
		print_r($MENU);
		exit();
	}
	$PAGE['menu'] = $MENU;
}

function util_set_ignored($dir, $MENU) {
	$MENU[$dir]['ignored'] = 1;
	if (is_array($MENU[$dir]['children']) and count($MENU[$dir]['children']))
		foreach($MENU[$dir]['children'] as $c)
			$MENU = util_set_ignored($c, $MENU);
	return $MENU;
}

/**
 * fetch & set moderators for directory
 * INSECURE but NON-VITAL --> requires MODERATE to be access_action_id #4 and MODERATE to be applied only to groups
 */
function fetch_moderators($dir_id) {
	global $PAGE;
	
	$did = $dir_id;
	$moderators = array();
	
	for ($i = $PAGE['dir_depth']-1; $i >= 0; $i--) {
		$did = $PAGE['directory_tree'][$i]['dir_id'];
		$sqlresult = db_do_query(db_query_select(array(array(), "MEMBER.nick"), 
							 array("(ACCESS_RULE INNER JOIN IN_USERGROUP ON ACCESS_RULE.usergroup_id = IN_USERGROUP.usergroup_id) " .
							       "INNER JOIN MEMBER ON IN_USERGROUP.user_id = MEMBER.user_id", "DUMMY"), 
							 "action_id = 4 AND dir_id = $did", "nick ASC"));
		while ($r = db_fetch_array($sqlresult))
			if (!in_array($r['nick'], $moderators))
				$moderators[] = $r['nick'];
	}
	
	$PAGE['moderators'] = $moderators;
}

/**
 * redirects to the supplied url immediately
 */
function redirect($url) {
	session_write_close();
	header("Location: $url");
	exit();
}

/**
 * redirects to the supplied error number
 */
function errorpage($error) {
	include_once('sys/errors.inc');
	endpage("{$ERROR[$error]}", "ERROR: $error");
	redirect("$error.error");
}

/**
 * simple stat function
 */
function getmicrotime() { 
	list($usec, $sec) = explode(" ",microtime()); 
	return ((float)$usec + (float)$sec); 
}

/**
 * adds an action to the current action array
 */
function add_action($id, $type, $action, $javascript = '', $major = 0) {
	global $PAGE;
	if (!is_array($PAGE['actions']))
		$PAGE['actions'] = array();
	switch($type) {
		case 'url':
			$action = "{$PAGE['dirpath']}/$action";
			break;
		case 'url-action':
			$action = "{$PAGE_INFO}?action=$action";
			break;
	}
	array_unshift($PAGE['actions'], array('id' => $id, 'type' => $type, 'action' => $action, 'javascript' => $javascript, 'major' => $major));
}

/**
 * adds an alert to the current alert array
 */
function add_alert($message, $link='', $target=0, $delete='') {
	global $PAGE;
	if ($target) {
		$sql = db_do_query(db_query_insert(array('user_id', 'alert'), array($target, db_sqlize($message)), "ALERT"));
	} else {
		if (!is_array($PAGE['alerts']))
			$PAGE['alerts'] = array();
		array_push($PAGE['alerts'], array('message' => $message, 'link' => $link, 'delete' => $delete));
		if ($delete)
			if ($PAGE['alerts_delete'])
				$PAGE['alerts_delete'] .= ",{$delete}";
			else
				$PAGE['alerts_delete'] .= $delete;
	}
}

function get_keys_and_values($keyfieldname, $valuefieldname, $table, $where=1, $order='') {
	$sql = db_query_select(array(array($keyfieldname, $valuefieldname)), array($table), $where, $order);
	$sqlresult = db_do_query($sql);
	$keys = array();
	$vals = array();
	while ($r = db_fetch_array($sqlresult)) {
		array_unshift($keys, $r[$keyfieldname]);
		array_unshift($vals, $r[$valuefieldname]);
	}
	return array('keys' => $keys, 'values' => $vals);
}

function get_keyed_values($keyfieldname, $valuefieldname, $table, $where=1, $order='') {
	$sql = db_query_select(array(array($keyfieldname, $valuefieldname)), array($table), $where, $order);
	$sqlresult = db_do_query($sql);
	$vals = array();
	while ($r = db_fetch_array($sqlresult))
		$vals[$r[$keyfieldname]] = $r[$valuefieldname];
	return $vals;
}

function add_log($string) {
	$sql = db_query_insert(array('log_date', 'log', 'ipstring'), array('NOW(14)', db_sqlize($string), 
				     db_sqlize($_SERVER["REMOTE_ADDR"]." - ".$_SERVER["HTTP_X_FORWARDED_FOR"])), 'LOG');
	db_do_query($sql);
}

function endpage($str, $title="") {
	global $PAGE, $no_menu, $CONFIG, $ECHO;
	// SAI specific !!!
	include_once("sys/skins/" . ($_SESSION['member']['pref_skin'] ? $_SESSION['member']['pref_skin'] : $CONFIG['default_skin']) . "/main.inc");
	print_header($PAGE['menu'], $title ? $title : "Resultaat van uw bewerking", $no_menu);
	print_body($str);
	print_footer("", 0, $no_menu, 0, 1);
	die($ECHO['echovar']);
}

function mdg_date_format($date, $informal=0, $hourlevel=0, $fullmonth=0) {

	$date = ereg_replace("[^0-9]", "", $date);
	
	$then = array(
		'year' => intval(substr($date, 0, 4)),
		'month' => intval(substr($date, 4, 2)), 
		'day' => intval(substr($date, 6, 2)), 
		'hour' => intval(substr($date, 8, 2)), 
		'min' => substr($date, 10, 2));

	if ($hourlevel > 0) // just hours
		return "{$then['hour']}u{$then['min']}";

	if ($informal) {
		$datestamp = "{$then['month']}/{$then['day']}/{$then['year']} {$then['hour']}:{$then['min']}";
		$now = date('U');
		$dif = $now - strtotime($datestamp);
		$fut = ($dif > 0) ? 0 : 1;
		$absdif = abs($dif);
		
		if ((intval(date('d')) == $then['day']) and (intval(date('m')) == $then['month']) and (intval(date('Y')) == $then['year'])) { 
		
			if ($hourlevel < 0)
				return "vandaag";
		
			if ($absdif < 3600) {
				if ($absdif < 900)
					if ($fut)
						return "over een kwartier";
					else
						return "een kwartier geleden";
				else if ($absdif < 1800)
					if ($fut)
						return "over een half uur";
					else
						return "een half uur geleden";
				else
					if ($fut)
						return "over een uur";
					else
						return "een uur geleden";
					
			} else if ($absdif < 21600)
				if ($fut)
					return "over " . intval($absdif / 3600) . " uur";
				else
					return intval($absdif / 3600) . " uur geleden";
			else
				return "vandaag";
				
		} else if ((intval(date('d', strtotime('-1 day'))) == $then['day']) and (intval(date('m', strtotime('-1 day'))) == $then['month']) 
				and (intval(date('Y', strtotime('-1 day'))) == $then['year']))
			return "gisteren" . (($hourlevel >= 0) ? ", {$then['hour']}u{$then['min']}" : "");
		else if ((intval(date('d', strtotime('-2 day'))) == $then['day']) and (intval(date('m', strtotime('-2 day'))) == $then['month']) 
				and (intval(date('Y', strtotime('-2 day'))) == $then['year']))
			return "eergisteren" . (($hourlevel >= 0) ? ", {$then['hour']}u{$then['min']}" : "");
		else if ((intval(date('d', strtotime('+1 day'))) == $then['day']) and (intval(date('m', strtotime('+1 day'))) == $then['month']) 
				and (intval(date('Y', strtotime('+1 day'))) == $then['year']))
			return "morgen" . (($hourlevel >= 0) ? ", {$then['hour']}u{$then['min']}" : "");
		else if ((intval(date('d', strtotime('+2 day'))) == $then['day']) and (intval(date('m', strtotime('+2 day'))) == $then['month']) 
				and (intval(date('Y', strtotime('+2 day'))) == $then['year']))
			return "overmorgen" . (($hourlevel >= 0) ? ", {$then['hour']}u{$then['min']}" : "");
	}
	
	if ($fullmonth) {
		$months = array(1 => 'januari', 2 => 'februari', 3 => 'maart',
				4 => 'april', 5 => 'mei', 6 => 'juni', 7 => 'juli',
				8 => 'augustus', 9 => 'september', 10 => 'oktober',
				11 => 'november', 12 => 'december');
		return "{$then['day']} {$months[$then['month']]} {$then['year']}" . (($hourlevel >= 0) ? ", {$then['hour']}u{$then['min']}" : "");	
	} else
		return "{$then['day']}-{$then['month']}-{$then['year']}" . (($hourlevel >= 0) ? ", {$then['hour']}u{$then['min']}" : "");
}

function get_last_clicks() {
	$online = db_do_query(db_query_select(array(array("user_id", "nick")), array("MEMBER"), 
					      "user_id != {$_SESSION['user_id']} AND (DATE_ADD(last_click, INTERVAL 10 MINUTE) > NOW(14))", "nick ASC"));
	$ol = array();
	if (db_num_rows($online))
		while($m = db_Fetch_array($online))
			$ol[] = $m;
	return $ol;
}
function click() {
	db_do_query(db_query_update(array('member_since', 'last_visit', 'last_click'), array('member_since', 'last_visit', 'NOW(14)'), "MEMBER", 
				    "user_id = {$_SESSION['user_id']}"));
}

?>
